AppID="46385963"
APIKEY="BWN9pwIZx6aoSjhSeGEiFikd"
secret_key="1cNeE3iG2czhcRtjsLrEuOul100bxKNI"
#APIKEY="fVkmSOXCgorPfvJ8Kl0ZKnIq"
#secret_key="pOReWqziKfQXXMJ4WJDwbvwjnKtm6LKj"

import requests,os
import json,time
import pandas as pd

def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+APIKEY+"&client_secret="+secret_key
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")

def main_google(i,title,author,desc):
    #apikey='AIzaSyD6tcwFInavhIbiniCsjsXiMWFNlpGgMOY'
    #apikey='AIzaSyCgm7jn2bCWa437cgKkJP1_OhdS1cyknHk'
    #apikey='AIzaSyAaVtOrZbUVkjeTvzvIw94__QGUlfmzGko'
    apikey='AIzaSyB7sK0vG1nRS8R9DK0QIG4F-p5Ncp2yhHc'
    #apikey='AIzaSyBsGFRYULu1yRMA_H-gdU4OvGivvqJDClM'
    url = f'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={apikey}'
    headers = {'Content-Type': 'application/json'}
    print(f'''Please output the following content for this work based on the title '{title}', author '{author}', and related description '{desc}': [Topic]: Topic \n [Keyword]: Keyword \n''')
    data = {
        'contents': [
            {
                'parts': [
                    {
                        'text': f'''Based on the title '{title}', author '{author}', and related description '{desc}' of the work, output follow text: [Topic]: Topic \\n [Keyword]: Keyword \\n'''
                        }
                    ]
                }
            ]
        }
    try:
        response = requests.post(url, headers=headers, data=json.dumps(data))
    except requests.exceptions.RequestException:
        return False
    response_text = response.json()
    print(response_text)
    if 'candidates' not in response_text or 'content' not in response_text['candidates'][0] or 'parts' not in response_text['candidates'][0]['content'] or 'text' not in response_text['candidates'][0]['content']['parts'][0]: return False
    result = "{"+"}".join("{".join(response_text['candidates'][0]['content']['parts'][0]['text'].split("{")[1:]).split("}")[:-2])+"}"
    with open("%d.md"%i,"w") as f:
        f.write(result+"\n")
    print(result)
    print(i)
    return True

def main(i,title,name,desc,token):
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=" + token
    payload = json.dumps({
            "messages": [
            {
                "role": "user",
                'content': f'''Based on the title '{title}', author '{name}', provide detailed data information in English as json style:''' + '{ "Genres": "[Genres]", "Synopsis": [Synopsis], "Reviews": [Review1,Review2,Review3], "Tags": [Tag1,Tag2,Tag3], "Related Books":[Related Book1, Related Book2, Related Book3]}'
            }
    ]
    })
    headers = {'Content-Type': 'application/json'}
    try:
        response = requests.request("POST", url, timeout=120, headers=headers, data=payload)
    except requests.exceptions.RequestException:
        return False
    result = json.loads(response.text)
    if 'result' not in result: return False
    else:
        with open("output_%d.json"%i,"w") as f:
            f.write(result['result']+"\n")
    print(response.text)
    print(i)
    return True
    
import sys
if __name__ == '__main__':
    token = get_access_token()
    for line in open('popular.txt',"r"):
        num,title = line.strip().split("\t")
        num = int(num)
        #if num not in [132,1727,4280,36,844]: continue
        if os.path.exists("output_%d.txt"%(num)) == False or os.path.exists("output_%d.pdf"%(num)) == False: continue
        name = ''
        title = ''
        tag = ''
        for i,item in enumerate(open("output_%d.txt"%(num),"r")):
            if i == 0:
                if item.count(", ") == 2:
                    n1,n2,p1 = item.split(", ")
                    name = n1+" "+n2
                else: name = item.split(", ")[0]
            elif i == 1: title = item.strip()
            elif i > 2: tag = item.replace("|",', ')
        print(num,title,name,tag)
        if os.path.exists("output_%d.json"%(num)): 
            print(num)
            json_data = json.loads(open("output_%d.json"%(num),"r").read().strip())
            continue
        ret = main(num,title,name,tag,token)
        cnt = 0
        while ret == False and cnt < 10:
            cnt += 1
            time.sleep(3) 
            ret = main(num,title,name,tag,token)
            if cnt<10:time.sleep(10) 
            else: break
